const express = require('express');
const app = express();
const path = require('path');
const favicon = require('serve-favicon');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const cluster = require('cluster');
const child_process = require('child_process');

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.set('env', 'production');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

const Promise = require('bluebird');
const config = require('./config');
const mongoose = require('mongoose');
mongoose.Promise = Promise;

mongoose.connect(config.connect + config.database, config.options);
const connection = mongoose.connection;
//数据库连接错误
connection.on('error', (err) => {
  console.log(err);
  app.use((req, res) => {
    return res.statue(500).send('数据库连接失败!')
  })
})
//数据库第一次连接
connection.once('open', () => {
  console.log('数据库连接成功')

  child_process.exec('node ./createRouter.js', (error, stdout, stderr) => {

    if (error) {
      console.error(`exec error: ${error}`);
      return;
    }
    console.log(`stdout: ${stdout}`);
    app.all('*', function (req, res, next) {
      res.header("Access-Control-Allow-Origin", "*");
      res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
      res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
      res.header("X-Powered-By", ' 3.2.1')
      if (req.method == "OPTIONS") res.send(200); /*让options请求快速返回*/
      else next();
    });
    app.use(require('./routes'));
    //添加路由文件

    // catch 404 and forward to error handler
    app.use(function (req, res, next) {
      const err = new Error('Not Found');
      err.status = 404;
      next(err);
    });

    // error handler
    app.use(function (err, req, res, next) {
      // set locals, only providing error in development
      res.locals.message = err.message;
      res.locals.error = req.app.get('env') === 'development' ? err : {};

      // render the error page
      res.status(err.status || 500);
      res.render('error');
    });
  })
});

//单机集群
if (cluster.isMaster) {
  var numWorkers = require('os').cpus().length;
  console.log('Master cluster setting up ' + numWorkers + ' workers...');

  for (let i = 0; i < numWorkers; i++) {
    cluster.fork();
    // .send('这是主进程发送的信息');
  }

  cluster.on('online', function (worker) {
    console.log('Worker ' + worker.process.pid + ' is online');
  });

  cluster.on('exit', function (worker, code, signal) {
    // console.log('Worker ' + worker.process.pid + ' died with code: ' + code + ', and signal: ' + signal);
    console.log('Starting a new worker');
    cluster.fork();
  });
  // Object.keys(cluster.workers).forEach(function (id) {
  //   cluster.workers[id].on('message', function (msg) {
  //     console.log('收到子进程消息:' + JSON.stringify(msg));
  //   });
  // });
} else {
  // process.on('message', function (msg) {
  //   console.log(cluster.worker.id + '收到主进程的信息:' + JSON.stringify(msg));
  //   process.send('这是子进程发送的消息');
  // });

  //创建http/https服务
  require('./bin/server')(app);
}

//单核服务
// require('./bin/server')(app);